package news.dao;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import org.apache.commons.dbutils.QueryRunner;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class DBTool {
    public static DataSource datasource;

    static {
        initWithConfigFile(); // 使用配置文件初始化数据源
    }

    static void initWithConfigFile() {
        // hashmap
        Properties p = new Properties();
        // 读取文件并封装为 键值对的 properties 对象
        InputStream is = DBTool.class.getResourceAsStream("/druid.properties");
        try {
            p.load(is);
            datasource = DruidDataSourceFactory.createDataSource(p);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static Connection getConnection() throws SQLException {
        return datasource.getConnection();
    }

    public static QueryRunner getQueryRunner() {
        return new QueryRunner(datasource);
    }

    /**
     * 执行非查询语句
     *
     * @param sql
     * @return
     * @throws SQLException
     */
    public static int executeUpdate(String sql) throws SQLException {
        Connection conn = datasource.getConnection();
        Statement st = conn.createStatement();
        int resultCount = st.executeUpdate(sql);
        close(conn, st, null);
        return resultCount;
    }

    public static int executeUpdate(String sql, Object[] params) throws SQLException {
        Connection conn = datasource.getConnection();// 获取连接
        PreparedStatement st = conn.prepareStatement(sql);//获取到预处理的sql对象
        if (params != null && params.length > 0) {
            for (int i = 0; i < params.length; i++) {
                // 给参数设置值
                // 注意：索引从1开始
                st.setObject(i + 1, params[i]);
            }
        }
        int resultCount = st.executeUpdate(); // 注意不要再给任何的参数
        close(conn, st, null);
        return resultCount;
    }


    public static void close(Connection conn, Statement st, ResultSet rs) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (st != null) {
            try {
                st.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
